/** @jsxImportSource react */

import { Button } from '~/components/react/shadcn/ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '~/components/react/shadcn/ui/dialog';
import { Plus } from 'lucide-react';
import { Input } from '~/components/react/shadcn/ui/input';
import { useState } from 'react';
import AlertMessage from '~/components/react/ui/AlertMessage';

type CreateCollectionProps = {
  onCreate: (title: string) => Promise<void>;
};

export default function CollectionCreator({ onCreate }: CreateCollectionProps) {
  const [title, setTitle] = useState('');
  const [open, setOpen] = useState(false);
  const [error, setError] = useState<string>('');
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger
        onClick={() => {
          setOpen(true);
          setTitle('');
        }}
      >
        <Plus size={16} className="cursor-pointer" />
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>添加新分类</DialogTitle>
        </DialogHeader>
        <div>
          <Input
            value={title}
            onChange={(e) => {
              setTitle(e.target.value);
              setError('');
            }}
            placeholder="分类名称"
          />
          {error && <AlertMessage title="保存分类失败" description={error} />}
        </div>
        <DialogFooter>
          <Button
            onClick={async () => {
              if (title) {
                try {
                  await onCreate(title);
                  setOpen(false);
                } catch (e) {
                  setError((e as Error).message || '未知错误');
                }
              }
            }}
          >
            保存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
